import React, { useState, useEffect } from 'react';
import MenuBar from '@/components/MenuBar/index';
import { PAGE } from '@/enums/common';
import Http from '@/utils/http';
import { Tabs } from 'antd-mobile';
import Lists from './components/Lists';
import { isEmpty } from 'project-libs';
import './index.less';
const order = function(props: any) {
  const [page, setPage] = useState(PAGE);
  const [orders, setOrders]: any = useState([]);
  const [showLoading, setShowLoading] = useState(true);
  const [type, setType] = useState(0);

  const invokeHttp = async (pageNum: number) => {
    const result = await Http({
      url: '/orders/lists',
      body: {
        ...page,
        pageNum,
        type,
      },
    });
    return result;
  };
  const fetchOrder = async (pageNum: number) => {
    const result: any = await invokeHttp(pageNum);
    if (!isEmpty(result) && result.length === page.pageSize) {
      setOrders(result);
      setShowLoading(true);
    } else if (!isEmpty(result) && result.length < page.pageSize) {
      setOrders(result);
      setShowLoading(false);
    } else {
      setShowLoading(false);
    }
  };

  const handleChange = (e: any) => {
    setType(e.sub);
    setPage(PAGE);
    setOrders([]);
    setShowLoading(true);
  };
  const tabs = [
    { title: '未支付', sub: 0 },
    { title: '已支付', sub: 1 },
  ];
  useEffect(() => {
    fetchOrder(1);
  }, [type]);
  const handleRefresh = async () => {
    const result: any = await invokeHttp(page.pageNum + 1);
    if (
      !isEmpty(orders) &&
      !isEmpty(result) &&
      result.length === page.pageSize
    ) {
      setOrders([...orders, ...result]);
      setPage({
        ...page,
        pageNum: page.pageNum + 1,
      });
      setShowLoading(true);
    } else {
      setShowLoading(false);
    }
  };

  return (
    <div>
      <MenuBar pathname="/order" />
      <div className="order-page">
        <Tabs tabs={tabs} onChange={handleChange}>
          <div className="tab">
            <Lists
              orders={orders}
              type={0}
              showLoading={showLoading}
              handleRefresh={handleRefresh}
            />
          </div>
          <div className="tab">
            <Lists
              orders={orders}
              type={1}
              showLoading={showLoading}
              handleRefresh={handleRefresh}
            />
          </div>
        </Tabs>
      </div>
    </div>
  );
};

export default order;
